<template>
  <div class="create-continer">
    <Card :style="{ padding: '0' }">
      <!-- 添加 ref 引用 -->
      <van-form ref="formRef">
        <!-- 客户号码 -->
        <van-field
          v-model="formData.customerPhone"
          label="客户号码"
          placeholder="请输入客户号码"
          input-align="right"
          :required="true"
          :rules="rules.customerPhone"
        />
        <!-- 单元区域 -->
        <DPicker
          v-model="formData.unit"
          is-link
          readonly
          label="单元区域"
          placeholder="请选择单元"
          :required="true"
          :rules="rules.unit"
          :list="store[dictNames.UNIT]"
        />
        <van-field
          v-model="formData.groupName"
          label="集团名称"
          placeholder="请输入集团名称"
          input-align="right"
          :required="true"
          :rules="rules.groupName"
        />
        <DPicker
          v-model="formData.groupType"
          is-link
          readonly
          label="集团类别"
          placeholder="请选择集团类别"
          :list="store[dictNames.GROUP_TYPE]"
        />
        <DPicker
          v-model="formData.customerTag"
          is-link
          readonly
          label="客户标识"
          placeholder="请选择客户标识"
          :list="store[dictNames.CUSTOMER_TAG]"
        />
        <DPicker
          v-model="formData.customerDemand"
          is-link
          readonly
          label="客户需求"
          placeholder="请选择客户需求"
          :required="true"
          :rules="rules.customerDemand"
          :list="store[dictNames.CUSTOMER_DEMAND]"
        />
        <van-field
          class="my-textarea"
          v-model="formData.description"
          rows="3"
          autosize
          label="问题描述"
          type="textarea"
          maxlength="200"
          placeholder="请输入工作内容"
          show-word-limit
          :required="true"
          :rules="rules.description"
        />
      </van-form>
    </Card>

    <div class="button-groups">
      <van-button
        :style="convertPxToRem('width: 165px')"
        @click="resetFormData"
        round
        plain
        >重置</van-button
      >
      <van-button
        :style="convertPxToRem('width: 165px')"
        round
        type="primary"
        @click="submitFormData"
        >确认创建</van-button
      >
    </div>
  </div>
</template>

<script setup>
import {
  showLoadingToast,
  closeToast,
  showSuccessToast,
} from "@/utils/toast.js";

import useDict from "@/store/dict.js";
import useTabIndex from "@/store/tabIndex.js";
import dictNames from "@/config/dict.js";
import { convertPxToRem, reloadCurrentRoute } from "@/utils/index.js";
import { omsnCreate } from "@/api/index.js";

import { useRouter } from "vue-router";
import { ref, reactive, onMounted } from "vue";

const rules = {
  customerPhone: [
    { required: true, message: "请输入客户号码" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:[38]\d|4[579]|5[0-35-9]|6[2567]|7[0-8]|9[189])\d{8}$/,
      message: "请输入正确的11位手机号",
    },
  ],
  unit: [{ required: true, message: "请选择单元" }],
  groupName: [{ required: true, message: "请输入集团名称" }],
  // groupType: [{ required: true, message: "请选择集团类别" }],
  // customerTag: [{ required: true, message: "请选择客户标识" }],
  customerDemand: [{ required: true, message: "请选择客户需求" }],
  description: [{ required: true, message: "请输入问题描述" }],
};

const [store, setDict] = useDict();
async function loadDicts() {
  await setDict([
    dictNames.UNIT,
    dictNames.GROUP_TYPE,
    dictNames.CUSTOMER_TAG,
    dictNames.CUSTOMER_DEMAND,
  ]);
}

const formData = reactive({
  customerPhone: "",
  unit: "",
  groupName: "",
  groupType: "",
  customerTag: "",
  customerDemand: "",
  description: "",
});

function resetFormData() {
  Object.keys(formData).forEach((key) => {
    formData[key] = "";
  });
}

//  useTabIndex
const [tabIndex, setTabIndex] = useTabIndex();
const router = useRouter();

// 添加对 van-form 组件的引用
const formRef = ref();
async function submitFormData() {
  try {
    // 触发表单验证
    await formRef.value?.validate();

    // 验证通过，执行提交逻辑
    showLoadingToast("数据提交中...");
    try {
      const { errors } = await omsnCreate(formData);
      if (errors && errors.length > 0) return;

      showSuccessToast("数据提交成功");
      // 可选：提交成功后重置表单
      resetFormData();
      //  修改 active，刷新页面，进入指定tab
      setTabIndex(2);
      reloadCurrentRoute(router);
    } catch (submitError) {
      console.error("提交失败:", submitError);
    }
  } catch (validateError) {
    // 验证失败，Vant会自动显示错误信息，这里可以添加额外处理
    console.log("表单验证失败:", validateError);
  } finally {
    closeToast();
  }
}

onMounted(async () => {
  showLoadingToast();
  await loadDicts();
  closeToast();
});
</script>

<style lang="scss" scoped>
/* 把 van-field 内部的 textarea 背景改掉 */
.my-textarea :deep(.van-field__control) {
  background-color: #f5f5f5; /* 想要的颜色 */
  border-radius: 8px;
  padding: 8px;
}

/* 仅对当前组件内的表单错误信息设置靠右显示 */
:deep(.van-form .van-field__error-message) {
  text-align: right;
}

.create-continer {
  display: flex;
  flex-direction: column;
  align-items: center;

  .button-groups {
    margin-top: 100px;
    padding-top: 16px;
    display: flex;
    width: 100%;
    height: 100px;
    justify-content: space-evenly;
    background: #fff;
    box-sizing: border-box;
  }
}
</style>